﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ProcelNasEscolas.Model.Fichas;
using ProcelNasEscolas.Model.Interfaces;
using ProcelNasEscolas.Model.Respostas;
using ProcelNasEscolas.Model;

namespace ProcelNasEscolas.Data
{
    public class ConcessionariaDao : AbstractCrudDao<ConcessionariaData>
    {
        public Concessionaria ToModelObject(ConcessionariaData concessionariaData)
        {
            Concessionaria concessionariaModel = new Concessionaria();
            concessionariaModel.Id = concessionariaData.Id;
            concessionariaModel.Nome = concessionariaData.Nome;

            return concessionariaModel;
        }

        public ConcessionariaData CreateOrUpdate(Concessionaria concessionariaModel)
        {
            try
            {
                ConcessionariaData concessionariaData = new ConcessionariaData();

                IList<ConcessionariaData> concessionarias = this.GetObjectContext().IEntidadeDataSet.OfType<ConcessionariaData>().Where(concessionaria => concessionaria.Id == concessionariaModel.Id).ToList();

                if (concessionarias.Count == 0)
                {
                    this.Add("IEntidadeDataSet", concessionariaData);
                }
                else
                {
                    concessionariaData= concessionarias.First();
                }

                concessionariaData.Nome = concessionariaModel.Nome;
                this.SaveChanges();

                return concessionariaData;
            }
            catch (Exception e)
            {
                System.Console.Out.WriteLine("" + e);
                return null;
            } 
        }

        public Concessionaria GetConcessionaria(int Id)
        {
            try
            {
                IList<ConcessionariaData> result = this.GetObjectContext().IEntidadeDataSet.OfType<ConcessionariaData>().Where(c => c.Id == Id).ToList();

                return this.ToModelObject(result.First());
            }
            catch (Exception e)
            {
                System.Console.Out.WriteLine("" + e);
                return null;
            }
        }

        public IList<Concessionaria> GetAll()
        {
            IList<ConcessionariaData> result = this.GetObjectContext().IEntidadeDataSet.OfType<ConcessionariaData>()
                 .ToList();
            IList<Concessionaria> concessionarias = new List<Concessionaria>();

            foreach (ConcessionariaData concessionaria in result)
            {
                concessionarias.Add(this.ToModelObject(concessionaria));
            }

            return concessionarias;
        }
    }
}